package com.travel.commons.aspect;

import com.travel.commons.annotation.SysLog;
import com.travel.commons.shiro.ShiroUserGetter;
import com.travel.modules.sys.service.SysLogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * 系统日志切面处理
 */
@Slf4j
@Aspect
@Component
public class SysLogAspect {
    @Resource
    private SysLogService sysLogService;

    @Pointcut("@annotation(com.travel.commons.annotation.SysLog)")
    public void MsgPointCut() {
    }

    @Around("MsgPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Object result = point.proceed();
        send(point, result);
        return result;
    }

    private void send(ProceedingJoinPoint point, Object result) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        SysLog logAnno = method.getAnnotation(SysLog.class);
        if (logAnno == null) {/* 没有注解则不处理 */
            return;
        }

        com.travel.modules.sys.entity.SysLog sysLog = new com.travel.modules.sys.entity.SysLog();
        @SuppressWarnings("unchecked")
        Map<String, Object> resMap = (Map<String, Object>) result;
        Integer code = (Integer) resMap.get("code");

        if (code != 0) {/* 业务异常 */
            return;
        }

        String id = (String) resMap.get("id");
        sysLog.setOpt(logAnno.value() + "，编号：" + ((id == null) ? '-' : id));
        sysLog.setUserId(ShiroUserGetter.getUserId());
        sysLog.setType(2);
        sysLogService.save(sysLog);
    }
}
